package com.example.rabc.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库连接管理器，使用双重检查锁定实现单例模式
 */
@Component
public class DatabaseConnectionManager {
    
    private static volatile DatabaseConnectionManager instance; // 单例实例
    private HikariDataSource dataSource; // 数据库连接池
    
    private DatabaseConnectionManager() {
        // 私有构造函数，防止外部实例化
        initializeDataSource();
    }
    
    public static DatabaseConnectionManager getInstance() {
        if (instance == null) {
            synchronized (DatabaseConnectionManager.class) {
                if (instance == null) {
                    instance = new DatabaseConnectionManager();
                }
            }
        }
        return instance;
    }
    
    private void initializeDataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://localhost:3306/rbac_system");
        config.setUsername("root");
        config.setPassword("1234");
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        
        // 连接池配置
        config.setMaximumPoolSize(20);
        config.setMinimumIdle(5);
        config.setConnectionTimeout(30000);
        config.setIdleTimeout(600000);
        config.setMaxLifetime(1800000);
        
        dataSource = new HikariDataSource(config);
    }
    
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    
    public void closeDataSource() {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.close();
        }
    }
    
    // 连接池监控信息
    public Map<String, Object> getPoolInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("activeConnections", dataSource.getHikariPoolMXBean().getActiveConnections());
        info.put("idleConnections", dataSource.getHikariPoolMXBean().getIdleConnections());
        info.put("totalConnections", dataSource.getHikariPoolMXBean().getTotalConnections());
        return info;
    }
}